<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-row>
                <el-button icon="el-icon-plus" type="primary" @click="addRolesFormDialog=true">添加角色</el-button>
            </el-row>
            <!--表格-->
            <el-table
                    :data="infoList"
                    border
                    v-loading="is_load"
                    stripe>
                <!--展开列 -->
                <el-table-column align="center" type="expand">
                    <template slot-scope="scope">
                        <el-row v-for="(item1,i1) in scope.row.children" :key="item1.id"
                                :class="{'bdtop':i1 == 0,'bdbottom':true,'vcenter':true}">
                            <!--渲染一级权限-->
                            <el-col :span="5">
                                <el-tag @close="tagClose(scope.row,item1.authName,item1.id)" closable type="primary">
                                    {{item1.authName}}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!--渲染二级权限-->
                            <el-col :span="19">
                                <el-row :class="{'bdtop': i2!==0,'vcenter':true}" v-for="(item2,i2) in item1.children"
                                        :key="item2.id">
                                    <el-col :span="8">
                                        <el-tag @close="tagClose(scope.row,item2.authName,item2.id)" closable
                                                type="success">
                                            {{item2.authName}}
                                        </el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <!--渲染三级权限-->
                                    <el-col :span="16">
                                        <el-tag closable
                                                @close="tagClose(scope.row,item3.authName,item3.id)"
                                                v-for="(item3,i3) in item2.children" type="warning" :key="item3.id">
                                            {{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column align="center" type="index"></el-table-column>
                <el-table-column align="center" label="角色名称" prop="roleName"></el-table-column>
                <el-table-column align="center" label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column align="center" prop="" label="操   作">
                    <template slot-scope="scope">
                        <el-button style="margin-right: 10px" size="mini" type="primary" icon="el-icon-edit"
                                   @click="getRolesById(scope.row.id)">
                            编辑
                        </el-button>
                        <el-popconfirm
                                placement="top"
                                confirmButtonText='好的'
                                cancelButtonText='不用了'
                                @onConfirm="delRoles(scope.row.id)"
                                icon="el-icon-info"
                                iconColor="red"
                                :title="`确定删除 【${scope.row.roleName}】 吗？`">
                            <el-button style="margin-right: 10px" size="mini" type="danger" slot="reference"
                                       icon="el-icon-delete">
                                删除
                            </el-button>
                        </el-popconfirm>
                        <el-tooltip class="item" effect="dark" content="权限分配" placement="top" :enterable="false">
                            <el-button size="mini" type="warning" icon="el-icon-setting"
                                       @click="showSetRightDialog(scope.row)">
                                权限
                            </el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!--添加角色弹窗-->
            <el-dialog title="添加角色"
                       :visible.sync="addRolesFormDialog"
                       :close-on-click-modal="false"
                       width="40%"
                       @close="closeDialog('addRolesForm')"
            >
                <!--对话框的按钮-->
                <el-form :model="addRolesForm" :rules="addRolesFormRules" ref="addRolesForm" status-icon>
                    <el-form-item label="角色名称" prop="roleName" label-width="11%">
                        <el-input prefix-icon="el-icon-user" v-model="addRolesForm.roleName" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="roleDesc" label-width="11%">
                        <el-input prefix-icon="el-icon-s-comment" v-model="addRolesForm.roleDesc" clearable></el-input>
                    </el-form-item>
                </el-form>
                <template slot="footer">
                    <div class="dialog-footer">
                        <el-button @click="addRolesFormDialog=false">取 消</el-button>
                        <el-button type="primary" @click="addRoles">确 定</el-button>
                    </div>
                </template>
            </el-dialog>
            <!--修改角色弹窗-->
            <el-dialog title="修改角色"
                       :visible.sync="updateRolesFormDialog"
                       :close-on-click-modal="false"
                       width="40%"
                       @close="closeDialog('updateRolesForm')"
            >
                <!--对话框的按钮-->
                <el-form :model="updateRolesForm" :rules="updateRolesFormRules" ref="updateRolesForm" status-icon>
                    <el-form-item label="角色名称" prop="roleName" label-width="11%">
                        <el-input prefix-icon="el-icon-user" v-model="updateRolesForm.roleName" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="roleDesc" label-width="11%">
                        <el-input prefix-icon="el-icon-s-comment" v-model="updateRolesForm.roleDesc"
                                  clearable></el-input>
                    </el-form-item>
                </el-form>
                <template slot="footer">
                    <div class="dialog-footer">
                        <el-button @click="updateRolesFormDialog=false">取 消</el-button>
                        <el-button type="primary" @click="updateRoles">确 定</el-button>
                    </div>
                </template>
            </el-dialog>
            <!--分配权限的dialog-->
            <el-dialog title="权限分配" :visible.sync="setRightDialog"
                       @close="initTreeDefaultKey">
                <!--权限树-->
                <el-tree
                        ref="treeKeys"
                        :data="treeList"
                        :props="treeProps"
                        node-key="id"
                        :default-expand-all="true"
                        :default-checked-keys="defaultKey"
                        show-checkbox>
                </el-tree>
                <template slot="footer">
                    <div class="dialog-footer">
                        <el-button @click="setRightDialog=false">取 消</el-button>
                        <el-button type="primary" @click="allotRights">确 定</el-button>
                    </div>
                </template>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
    import $axios from '../../network/request'

    export default {
        name: "Roles",
        data() {
            return {
                //初始化数据
                infoList: [],
                //添加用户
                addRolesFormDialog: false,
                addRolesForm: {
                    roleName: "",
                    roleDesc: ""
                },
                addRolesFormRules: {
                    roleName: [
                        {required: true, message: '角色名称', trigger: 'blur'},
                        {min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur'}
                    ],
                    roleDesc: [
                        {required: true, message: '请输入角色描述', trigger: 'blur'},
                        {min: 5, max: 16, message: '长度在 5 到 16 个字符', trigger: 'blur'}
                    ],
                },
                //修改用户
                updateRolesFormDialog: false,
                updateRolesForm: {},
                updateRolesFormRules: {
                    roleName: [
                        {required: true, message: '角色名称', trigger: 'blur'},
                        {min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur'}
                    ],
                    roleDesc: [
                        {required: true, message: '请输入角色描述', trigger: 'blur'},
                        {min: 5, max: 16, message: '长度在 5 到 16 个字符', trigger: 'blur'}
                    ],
                },
                //删除对应权限
                roleName: '',
                authName: '',
                roleId: 0,
                //分配权限
                setRightDialog: false,
                treeList: [],
                treeProps: {
                    //绑定数型数据里面对应的属性值
                    label: 'authName',
                    children: 'children',
                },
                //设置默认勾选的CheckBox  此时必须设置node-key，其值为节点数据中的一个字段名，该字段在整棵树中是唯一的
                // 比如当前业务逻辑数据中的 id,或者authName
                defaultKey: [],
            }
        },
        methods: {
            //初始化表格
            init() {
                $axios({
                    method: 'get',
                    url: 'roles'
                }).then(res => {
                    if (res.data.meta.status !== 200) {
                        this.$message.error("数据请求异常")
                    } else {
                        this.infoList = res.data.data
                    }
                })
            },
            // 弹窗关闭，初始化弹窗
            closeDialog(formName) {
                this.$refs[formName].resetFields()
            },
            //添加角色
            addRoles() {
                this.$refs.addRolesForm.validate(valid => {
                    if (valid) {
                        $axios({
                            url: 'roles',
                            method: 'post',
                            data: this.addRolesForm
                        }).then(res => {
                            if (res.data.meta.status !== 201) {
                                this.$message.error("数据添加失败")
                            } else {
                                this.$message.success("添加成功")
                                this.init()
                                this.addRolesFormDialog = false
                            }
                        })
                    }
                })
            },
            //根据ID查询角色
            getRolesById(id) {
                $axios({
                    url: `roles/${id}`,
                    method: 'get'
                }).then(res => {
                    if (res.data.meta.status !== 200) {
                        this.$message.error("请求失败")
                    } else {
                        this.updateRolesFormDialog = true
                        this.updateRolesForm = res.data.data
                    }
                })
            },
            //修改角色
            updateRoles() {
                this.$refs.updateRolesForm.validate(valid => {
                    if (valid) {
                        $axios({
                            url: `roles/${this.updateRolesForm.roleId}`,
                            method: 'put',
                            data: this.updateRolesForm
                        }).then(res => {
                            if (res.data.meta.status !== 200) {
                                this.$message.error("修改失败")
                            } else {
                                this.$message.success("修改成功")
                                this.init()
                                this.updateRolesFormDialog = false
                            }
                        })
                    }
                })
            },
            //删除角色
            delRoles(rolesId) {
                $axios({
                    method: 'delete',
                    url: `roles/${rolesId}`,
                }).then(res => {
                    if (res.data.meta.status !== 200) {
                        this.$message.error("删除失败")
                    } else {
                        this.init()
                        this.$message.success("删除成功")
                    }
                })
            },
            //删除对应权限标签点击事件
            tagClose(scope, name, id) {
                this.roleName = scope.roleName;
                this.authName = name
                const h = this.$createElement;
                this.$msgbox({
                    title: '提示',
                    message: h('p', null, [
                        h('span', null, '确认删除 '),
                        h('i', {style: 'color: red'}, this.roleName),
                        h('span', null, ' 下对应的 '),
                        h('i', {style: 'color: red'}, this.authName),
                        h('span', null, '  权限吗?'),
                    ]),
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    beforeClose: (action, instance, done) => {
                        if (action === 'confirm') {
                            instance.confirmButtonLoading = true;
                            instance.confirmButtonText = '执行中...';
                            $axios({
                                method: 'delete',
                                url: `roles/${scope.id}/rights/${id}`
                            }).then(res => {
                                done()
                                instance.confirmButtonLoading = false;
                                if (res.data.meta.status !== 200) {
                                    this.$message.error("删除权限失败")
                                } else {
                                    // 返回的data, 是当前角色下最新的权限数据,所以只需要把data数据复制给传进来的传输即可
                                    this.$message.success('删除权限成功');
                                    scope.children = res.data.data
                                }
                            })
                        } else {
                            this.$message.info("您取消了删除")
                            done()
                        }
                    }
                })
            },
            //分配权限的dialog
            showSetRightDialog(scope) {
                this.roleId = scope.id;
                this.setRightDialog = true
                $axios({
                    method: 'get',
                    url: 'rights/tree'
                }).then(res => {
                    if (res.data.meta.status !== 200) {
                        this.$message.error("请求数据失败")
                    } else {
                        this.treeList = res.data.data;
                        this.getTreeKey(scope, this.defaultKey)
                    }
                })
            },
            //通过递归的形式获取角色下所有的三级权限的id
            getTreeKey(node, arr) {
                if (!node.children) {
                    arr.push(node.id)
                } else {
                    node.children.forEach(item => {
                        this.getTreeKey(item, arr)
                    })
                }
            },
            initTreeDefaultKey() {
                //初始化默认定义的数组
                this.defaultKey = [];
            },
            //分配权限
            allotRights() {
                const key = this.$refs.treeKeys
                const allKey = key.getCheckedKeys().concat(key.getHalfCheckedKeys())
                const allKeyStr = allKey.join(',')
                $axios({
                    method: 'post',
                    url: `roles/${this.roleId}/rights`,
                    data: {
                        rids: allKeyStr
                    }
                }).then(res => {
                        if (res.data.meta.status !== 200) {
                            this.$message.error("分配权限失败")
                        } else {
                            this.setRightDialog = false,
                                this.$message.success("分配权限成功")
                            this.init()
                        }
                    }
                )
            }
        },

        created() {
            this.init()
        },
        computed: {
            is_load() {
                return this.$store.state.is_loading
            },

        }
    }
</script>

<style lang="less" scoped>

    .vcenter {
        display: flex;
        align-items: center;
    }

</style>
